package work.xiaohong.jijin.controller;

import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import work.xiaohong.jijin.entity.Zixuan;
import work.xiaohong.jijin.entity.lianghua.*;
import work.xiaohong.jijin.feign.QQEmailFeign;
import work.xiaohong.jijin.service.IZixuanService;
import work.xiaohong.model.Result;
import work.xiaohong.model.StatusCode;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.Collectors;

/**
 * @author xiaohong
 * @version 1.0
 * @date 2021/11/20 0020 16:35
 * @description 量化自选接口
 */
@Tag(name = "量化自选接口文档")
@RestController
@Slf4j
@RequestMapping("/lianghua")
public class LiangHuaController {

    @Autowired
    private IZixuanService iZixuanService;

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    @Autowired
    private QQEmailFeign qqEmailFeign;

    public static void main(String[] args) {
//        String json = "{\"symbol\":\"circle\",\"symbolSize\":\"5.7\",\"data\":[{\"coord\":[\"2021-11-22\",\"1.3451\"],\"itemStyle\":{\"color\":\"#FFC817\",\"borderWidth\":\"1.1\",\"borderType\":\"solid\",\"borderColor\":\"#FFFFFF\"}}]}";
//        System.out.println(JSON.parseObject(json).getObject("data",List.class).get(0));

        List<Integer> list = Arrays.asList(1,432,123,54,12,3,5,23,43);
        System.out.println(list);
        List newList = list.stream().sorted((a,b) -> {
            System.out.println("a--->"+a+"-----b----->"+b);
            return b.compareTo(a);
        }).collect(Collectors.toList());
        System.out.println(newList);

    }

    /***
     * 登录量化
     * @return
     */
    @Operation(summary = "登录量化",description = "所需权限：",security ={@SecurityRequirement(name ="Authorization")})
    @PostMapping("/login")
    public Result<LiangHuaUser> Login(){
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("authCode", DigestUtil.md5Hex(LocalDateTime.now().toString()));

        String result = HttpRequest.post("https://www.lianghuazixuan.com/api/loginwx")
                .header(Header.HOST, "www.lianghuazixuan.com")
                .header(Header.USER_AGENT, "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36 MicroMessenger/7.0.9.501 NetType/WIFI MiniProgramEnv/Windows WindowsWechat")
                .header(Header.CONTENT_TYPE, "application/json")
                .header(Header.REFERER, "https://servicewechat.com/wx073f9b018ef83170/12/page-frame.html")
                .header(Header.ACCEPT_ENCODING, "gzip, deflate, br")
                .form(paramMap)//表单内容
                .timeout(20000)//超时，毫秒
                .execute().body();
        try {
            LiangHuaUser liangHuaUser = JSON.parseObject(result, LiangHuaUser.class);

            // 修改量化配置
            HashMap<String, Object> configMap = new HashMap<>();
            configMap.put("alipayid", liangHuaUser.getAlipayid());
            configMap.put("ma5", "5"); // 5日线
            configMap.put("ma30", "30"); // 30日线
            configMap.put("ma60", "60"); // 60日线
            configMap.put("policyid", "0"); // 卖出策略 0 激进 1 中庸 2 保守
            String configJson = JSON.toJSONString(configMap);
            String configResult = HttpRequest.post("https://www.lianghuazixuan.com/api/user/addconfig")
                    .header(Header.HOST, "www.lianghuazixuan.com")
                    .header(Header.USER_AGENT, "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36 MicroMessenger/7.0.9.501 NetType/WIFI MiniProgramEnv/Windows WindowsWechat")
                    .header(Header.CONTENT_TYPE, "application/json")
                    .header(Header.REFERER, "https://servicewechat.com/wx073f9b018ef83170/12/page-frame.html")
                    .header(Header.ACCEPT_ENCODING, "gzip, deflate, br")
                    .header("authtoken", liangHuaUser.getAuthtoken())
                    .body(configJson)
                    .timeout(20000)//超时，毫秒
                    .execute().body();
            if (JSON.parseObject(configResult).getString("msg").equals("修改完成")){
                return new Result<LiangHuaUser>(true, StatusCode.OK.getCode(),"登录成功",liangHuaUser) ;
            }else {
                return new Result<LiangHuaUser>(true, StatusCode.ERROR.getCode(),"登录失败") ;
            }

        }catch (Exception e){
            e.printStackTrace();
            return new Result<LiangHuaUser>(true, StatusCode.ERROR.getCode(),"登录失败") ;
        }
    }


    /***
     * 判断当前用户的vip消息
     * @return
     */
    @Operation(summary = "判断当前用户的vip消息",description = "所需权限：",security ={@SecurityRequirement(name ="Authorization")})
    @PostMapping("/isvip")
    public Result<LiangHuaVip> isVip(@RequestBody LiangHuaQuery liangHuaQuery){
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("alipayid", liangHuaQuery.getAlipayid());
        String json = JSON.toJSONString(paramMap);
        String result = HttpRequest.post("https://www.lianghuazixuan.com/api/isvip")
                .header(Header.HOST, "www.lianghuazixuan.com")
                .header(Header.USER_AGENT, "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36 MicroMessenger/7.0.9.501 NetType/WIFI MiniProgramEnv/Windows WindowsWechat")
                .header(Header.CONTENT_TYPE, "application/json")
                .header(Header.REFERER, "https://servicewechat.com/wx073f9b018ef83170/12/page-frame.html")
                .header(Header.ACCEPT_ENCODING, "gzip, deflate, br")
                .header("authtoken", liangHuaQuery.getAuthtoken())
                .body(json)
                .timeout(20000)//超时，毫秒
                .execute().body();
        try {
            LiangHuaVip liangHuaVip = JSON.parseObject(result, LiangHuaVip.class);
            return new Result<LiangHuaVip>(true, StatusCode.OK.getCode(),"查询vip成功",liangHuaVip) ;
        }catch (Exception e){
            e.printStackTrace();
            return new Result<LiangHuaVip>(true, StatusCode.ERROR.getCode(),"查询vip失败") ;
        }
    }


    /***
     * 获取近30天的买卖点
     * @return
     */
    @Operation(summary = "获取近30天的买卖点",description = "所需权限：",security ={@SecurityRequirement(name ="Authorization")})
    @PostMapping("/point")
    public Result<LiangHuaPoint> getPoint(@RequestBody LiangHuaQuery liangHuaQuery){
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("fundcode", liangHuaQuery.getCode());
        paramMap.put("day", "30");
        String json = JSON.toJSONString(paramMap);

        String result = HttpRequest.post("https://www.lianghuazixuan.com/api/fund/buypoint")
                .header(Header.HOST, "www.lianghuazixuan.com")
                .header(Header.USER_AGENT, "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36 MicroMessenger/7.0.9.501 NetType/WIFI MiniProgramEnv/Windows WindowsWechat")
                .header(Header.CONTENT_TYPE, "application/json")
                .header(Header.REFERER, "https://servicewechat.com/wx073f9b018ef83170/12/page-frame.html")
                .header(Header.ACCEPT_ENCODING, "gzip, deflate, br")
                .header("authtoken", liangHuaQuery.getAuthtoken())
                .body(json)
                .timeout(20000)//超时，毫秒
                .execute().body();
        try {
            LiangHuaPoint liangHuaPoint = JSON.parseObject(result, LiangHuaPoint.class);
            return new Result<LiangHuaPoint>(true, StatusCode.OK.getCode(),"获取买卖点成功",liangHuaPoint) ;
        }catch (Exception e){
            e.printStackTrace();
            return new Result<LiangHuaPoint>(true, StatusCode.ERROR.getCode(),"获取买卖点失败") ;
        }
    }

    /***
     * 获取量化策略列表
     * @return
     */
    @Operation(summary = "获取量化策略列表",description = "所需权限：",security ={@SecurityRequirement(name ="Authorization")})
    @PostMapping("/all")
    public Result<List<LiangHuaReponse>> getAll(@RequestBody LiangHuaQuery liangHuaQuery) throws InterruptedException {
        // 获取所有自选列表
        List<Zixuan> zixuans = iZixuanService.list();

        if (zixuans == null || zixuans.size() <= 0){
            return new Result(true, StatusCode.ERROR.getCode(),"量化策略列表为空",null) ;
        }

        List<LiangHuaReponse> resultList = new ArrayList();

        // 是否请求异常标志
        boolean flag = false;

        for (Zixuan zixuan : zixuans) {
            // 遍历获取自选策略
            LiangHuaReponse liangHuaReponse = new LiangHuaReponse();
            liangHuaReponse.setCode(zixuan.getCode());
            liangHuaReponse.setName(zixuan.getName());
            liangHuaQuery.setCode(zixuan.getCode()+"");

            if(flag){
                resultList.add(liangHuaReponse);
                continue;
            }

            LiangHuaPoint data = getPoint(liangHuaQuery).getData();

            if (data == null){
                // 请求失败
                flag = true;
            }else if (data.getData() == null || data.getData().size() <= 0){
                // 没有权限
                flag = true;
            }else if ("#FFC817".equals(data.getData().get(0).getItemStyle().getColor())){
                // 观望
                liangHuaReponse.setIdea(1);
            }else if ("#F35833".equals(data.getData().get(0).getItemStyle().getColor())){
                // 买入
                liangHuaReponse.setIdea(2);
            }else if ("#1C86EE".equals(data.getData().get(0).getItemStyle().getColor())){
                // 卖出
                liangHuaReponse.setIdea(3);
            }else {
                // 灵异事件
                flag = true;
            }
            resultList.add(liangHuaReponse);

            // 休息0.1s再查
            Thread.sleep(100);
        }

        //排个序
        List<LiangHuaReponse> result = resultList.stream().sorted((a,b) -> b.getIdea().compareTo(a.getIdea()))
                .collect(Collectors.toList());

        return new Result<List<LiangHuaReponse>>(true, StatusCode.OK.getCode(),"获取量化策略列表成功",result);

    }


}
